package com.smasher.dialog.select.model

import android.util.Log
import androidx.paging.PagingSource
import androidx.paging.PagingState

class TargetPagingSource<T : Any>(
    val backend: TargetBackendService,
    val query: String
) : PagingSource<Int, T>() {

    /**
     * Load data for the given page
     */
    override suspend fun load(
        params: LoadParams<Int>
    ): LoadResult<Int, T> {
        try {
            // Start refresh at page 1 if undefined.
            val current = params.key ?: 1

            Log.e(TAG, "load: $current")
            val list: List<T> = backend.searchUsers(query, current) as List<T>
            val next = if (list.isEmpty()) {
                null
            } else {
                current + 1
            }
            return LoadResult.Page(
                data = list,
                prevKey = null, // Only paging forward.
                nextKey = next
            )

        } catch (e: Exception) {
            // Handle errors in this block and return LoadResult.Error for
            // expected errors (such as a network failure).
            return LoadResult.Error(e)
        }
    }

    override fun getRefreshKey(state: PagingState<Int, T>): Int? {
        // Try to find the page key of the closest page to anchorPosition from
        // either the prevKey or the nextKey; you need to handle nullability
        // here.
        //  * prevKey == null -> anchorPage is the first page.
        //  * nextKey == null -> anchorPage is the last page.
        //  * both prevKey and nextKey are null -> anchorPage is the
        //    initial page, so return null.
        return state.anchorPosition?.let { anchorPosition ->
            val anchorPage = state.closestPageToPosition(anchorPosition)
            anchorPage?.prevKey?.plus(1) ?: anchorPage?.nextKey?.minus(1)
        }
    }

    companion object {
        const val TAG = "TargetPagingSource"
    }
}